<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false"
    :close-on-press-escape="false">
    <el-form :inline="true" :model="dataForm" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
      label-width="120px">
      <el-form-item label="市级" prop="city">
        <el-tree-select v-model="dataForm.city" :data="citySelectData" :render-after-expand="false" style="width: 240px"
          @current-change="cityChange" />
      </el-form-item>
      <el-form-item label="区级" prop="area">
        <el-tree-select v-model="dataForm.area" :data="distinguishSelectData" :render-after-expand="false"
          style="width: 240px" @current-change="areaChange" />
      </el-form-item>
      <el-form-item label="街道" prop="street">
        <el-tree-select v-model="dataForm.street" :data="streetSelectData" :render-after-expand="false"
          style="width: 240px" @current-change="streetChange" />
      </el-form-item>
      <el-form-item label="行政村" prop="adminVillage">
        <el-tree-select v-model="dataForm.adminVillage" :data="adminVillageSelectData" :render-after-expand="false"
          style="width: 240px" @current-change="adminVillageChange" />
      </el-form-item>
      <el-form-item label="自然村" prop="naturalVillageName">
        <el-input v-model="dataForm.naturalVillageName" placeholder="自然村名" style="width: 240px"></el-input>
      </el-form-item>
      <el-form-item label="村庄类型" prop="villageType">
        <el-input v-model="dataForm.villageType" placeholder="村庄类型" style="width: 240px"></el-input>
      </el-form-item>
      <el-form-item label="村庄全称" prop="villageName">
        <el-input v-model="dataForm.villageName" placeholder="村庄全称" style="width: 240px"></el-input>
      </el-form-item>
      <el-form-item label="农户数" prop="farmerNumber">
        <el-input v-model="dataForm.farmerNumber" placeholder="农户数" style="width: 240px"></el-input>
      </el-form-item>
      <el-form-item label="经纬度" prop="lng">
        <span>{{ curLonLat ||  dataForm.lng ?  `${dataForm.lng},${dataForm.lat}` : '' }}</span>
        <MapChoose :atLocation="MapData.placeLoc" :address="MapData.placeName" @get-location="getLocation"
          style="margin-left: 10px" />

      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="dataForm.status" inline-prompt :active-value="1" :inactive-value="0" active-text="正常" inactive-text="停用" />
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, reactive, ref, watch } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
import { treeDataTranslate } from "@/utils/utils";
import { transformData, getNestedStructure, findObjectByPid } from "@/utils/utils";
import MapChoose from "@/components/MapChoose/index.vue"


const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const dataFormRef = ref();
const MapData = reactive<any>({
  placeLoc: '',
  placeName: '',
});
const curLonLat = ref();
const dataForm = reactive({
  // id: "",
  // name: "",
  city: "",
  cityName: "",
  area: "",
  areaName: "",
  street: "",
  streetName: "",
  adminVillage: "",
  adminVillageName: "",
  naturalVillage: "",
  naturalVillageName: "",
  villageType: "",
  villageName: "",
  farmerNumber: "",
  status: 0,
  lng: "",
  lat: "",
});

const regionData = ref<any>();

// 市，区，街道，行政村
const citySelectData = ref<any>();
// 区数据
const distinguishSelectData = ref<any>();
// 街道数据
const streetSelectData = ref<any>();
// 行政村
const adminVillageSelectData = ref<any>();

const rules = ref({
  
  city: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }],
  area: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }],
  street: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }],
  name: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }],
  adminVillage: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }],
  naturalVillageName: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }],
  villageType: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }],
  farmerNumber: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }],
  villageName: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }],
  lat: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }],
  lng: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }],
  status: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }],
});

onMounted(() => {
  getAreaRegion();
});

const getDistinguishRegionData = (id: any) => {
  distinguishSelectData.value = findObjectByPid(regionData.value, id)?.map((item: any) => {
    return {
      value: item.id,
      label: item.name,
      // pid: item.pid
    }
  })
}

const cityChange = (e: any = {}) => {
  const { children, value, label } = e
  if (!children) {
    dataForm.cityName = label;
    dataForm.city = value;
  }
  dataForm.area = '';
  dataForm.street = '';
  dataForm.adminVillage = '';
  getDistinguishRegionData(e.value)
}

const getStreetRegion = (id: any) => {
  streetSelectData.value = findObjectByPid(regionData.value, id)?.map((item: any) => {
    return {
      value: item.id,
      label: item.name,
      pid: item.pid
    }
  })
}

const areaChange = (e: any = {}) => {
  const { children, value, label } = e
  if (!children) {
    dataForm.areaName = label;
    dataForm.area = value;
  }
  dataForm.street = '';
  dataForm.adminVillage = '';
  getStreetRegion(e.value)

}

const getAdminVillageRegion = (id: any) => {
  adminVillageSelectData.value = findObjectByPid(regionData.value, id)?.map((item: any) => {
    return {
      value: item.id,
      label: item.name,
      pid: item.pid
    }
  })
}
const streetChange = (e: any = {}) => {
  const { children, value, label } = e
  if (!children) {
    dataForm.streetName = label;
    dataForm.street = value;
  }
  dataForm.adminVillage = '';
  getAdminVillageRegion(e.value)
}

const adminVillageChange = (e: any = {}) => {
  const { children, value, label } = e
  if (!children) {
    dataForm.adminVillageName = label;
    dataForm.adminVillage = value;
  }
}

const getAreaRegion = () => {
  baseService.get("/sys/region/tree").then((res) => {
    const JSRegion = treeDataTranslate(res.data)?.find((item: any) => item.name === '江苏省')?.children
    regionData.value = JSRegion;
    citySelectData.value = JSRegion?.map((item: any) => {
      return {
        value: item.id,
        label: item.name,
        pid: item.pid
      }
    })
  });
}

const init = (id?: number) => {
  visible.value = true;
  // dataForm.id = "";

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  if (id) {
    getInfo(id);
  }
};

const getLocation = (obj: any) => {// 组件返回的经纬度和地址名称
  dataForm.lng = obj?.longitude
  dataForm.lat = obj?.latitude
  curLonLat.value = obj?.longitude + ' , ' + obj?.latitude;
}


// 获取信息
const getInfo = (id: number) => {
  baseService.get("/assess/point/" + id).then((res) => {
    Object.assign(dataForm, res.data);
    // 初始化区域下拉
    if (res.data) {
      const { city, area, street, adminVillage } = res.data;
      nextTick(() => {
        getDistinguishRegionData(city);
        getStreetRegion(area);
        getAdminVillageRegion(street);
      })
    }
  });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    (!dataForm.id ? baseService.post : baseService.put)("/assess/point", dataForm).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};


defineExpose({
  init
});
</script>
<style scoped>
::v-deep .cuteMap .cuteMap-header .cuteMap-header-search .serarchInput {
  display: none;
}
</style>